package com.paireach.bw.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.trace.TraceLocation;
import com.bumptech.glide.Glide;
import com.nanchen.compresshelper.CompressHelper;
import com.orhanobut.logger.Logger;
import com.paireach.bw.R;
import com.paireach.bw.adapter.KaRejectGridViewAdapter;
import com.paireach.bw.application.MyApplication;
import com.paireach.bw.base.BaseActivity;
import com.paireach.bw.bean.LocationInfo;
import com.paireach.bw.bean.ReturnInfo;
import com.paireach.bw.common.Constant;
import com.paireach.bw.http.MainRequest;
import com.paireach.bw.http.NetUrl;
import com.paireach.bw.interface2.LocateCallback;
import com.paireach.bw.utils.BDTraceUtil;
import com.paireach.bw.utils.GsonUtil;
import com.paireach.bw.utils.LogUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import es.dmoral.toasty.Toasty;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;

/**
 * Created by ${cqc} on 2017/3/21.
 * "配送中"
 */

public class DriverExceptionPostActivity extends BaseActivity {

    private static final String TAG = "DriverExceptionPostActivity";
    private Toolbar toolbar;
    private EditText et_order_code;
    private EditText et_exception_text;
    private List<String> pathList = new ArrayList<>();
    ;
    private String orderCode;
    private GridView gridview;
    private KaRejectGridViewAdapter gridViewAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
            Transition slide_bottom = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_bottom);
            getWindow().setEnterTransition(slide_bottom);
        }
        setContentView(R.layout.activity_driver_exception_post);
        orderCode = getIntent().getStringExtra("orderCode");
        findViews();
        initViews();
    }

    private void initViews() {
        toolbar.setTitle("异常上报");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        toolbar.inflateMenu(R.menu.exception_post_toolbar_menu);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.post_exception:
                        final String order_code = et_order_code.getText().toString();
                        final String remark = et_exception_text.getText().toString();
                        if (TextUtils.isEmpty(order_code)) {
                            showToast("单号不能为空");
                            return true;
                        }
                        if (TextUtils.isEmpty(remark)) {
                            showToast("异常详情不能为空");
                            return true;
                        }
//                        if (null == pathList || 0 == pathList.size()) {
//                            showToast("必须上传图片");
//                            return true;
//                        }
                        int size = pathList.size();
                        Map<String, File> map = new HashMap<>();
                        for (int i = 0; i < size; i++) {
                            File oldFile = new File(pathList.get(i));
                            File newFile = CompressHelper.getDefault(context).compressToFile(oldFile);
                            map.put(newFile.getName(), newFile);
                        }
                        showProgressDialog();
                        LocationInfo location = ((MyApplication) getApplication()).locationInfo;
                        OkHttpUtils.post()
                                .url(NetUrl.zhuang + "uploadAbnormalPresentationInfo.a")
                                .addParams("driverTel", phoneNumber)
                                .addParams("driverName", name)
                                .addParams("orderCode", order_code)
                                .addParams("remark", remark+"")
                                .files("file", map)
                                .addParams("lng", location.getLongitude() + "")
                                .addParams("lat", location.getLatitude() + "")
                                .build()
                                .execute(new MyStringCallback());
                        break;
                }
                return true;
            }
        });
        et_order_code.setText(orderCode);

        gridViewAdapter = new KaRejectGridViewAdapter(this, pathList);
        gridview.setAdapter(gridViewAdapter);
    }


    public class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {
            e.printStackTrace();
            LogUtil.d(TAG, "e=" + e.getMessage());
            showToast("图片上传失败");
            dismissProgressDialog();
        }

        @Override
        public void onResponse(String response, int id) {
            LogUtil.d(TAG, "onResponse=" + response + ",id=" + id);
            dismissProgressDialog();
            ReturnInfo info = GsonUtil.jsonToBean(response, ReturnInfo.class);
            if (info == null) {
                showToast("解析json错误，请联系服务端和客户端检查json数据");
            } else {
                showToast(info.getMsg());
                if (info.getStatus() == 1) {
                    finish();
                }
            }
        }
    }

    private void findViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        et_order_code = (EditText) findViewById(R.id.et_order_code);
        et_exception_text = (EditText) findViewById(R.id.et_exception_text);
        gridview = (GridView) findViewById(R.id.gridView_photo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.Integer_120 && resultCode == RESULT_OK) {
            // 获取返回的图片列表
            if (pathList != null) {
                pathList.clear();//清除之前的图片
            }
            if (data != null) {
                pathList.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));
                if (pathList.size() > 0) {
                    gridViewAdapter.notifyDataSetChanged();
                } else {
                    showToast("您没有选择任何图片");
                }
            }
        }
    }

}
